package com.example.goodtrash.Fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.goodtrash.R;
import com.example.goodtrash.search.ViewPaperAdapter;
import com.example.goodtrash.search.imageSearch;
import com.example.goodtrash.model.HotSearch;
import com.example.goodtrash.model.News;
import com.example.goodtrash.search.textSearch;
import com.example.goodtrash.util.HttpUtil;
import com.example.goodtrash.util.Utility;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class SearchFragment extends Fragment {
    private ProgressDialog progressDialog;
    private List<News> dataList=new ArrayList<>();
    private NewsAdapter adapter;
    private RecyclerView recyclerView;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private AppBarLayout appBarLayout;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private ViewPager2 viewPager2;
    private int lastPosition;                           //记录轮播图最后所在的位置
    private List<Integer> colors = new ArrayList<>();   //轮播图的颜色
    private LinearLayout indicatorContainer;            //填充指示点的容器
    private Handler mHandler = new Handler();
    private String mParam1;
    private String mParam2;


    public SearchFragment() {
        // Required empty public constructor
    }


    public static SearchFragment newInstance(String param1, String param2) {
        SearchFragment fragment = new SearchFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       View view=inflater.inflate(R.layout.fragment_search, container, false);
        Button TextSearch=(Button) view.findViewById(R.id.bt_text_search);
        Button VoiceSearch=(Button) view.findViewById(R.id.bt_voice_search);
        Button pictureSearch=view.findViewById(R.id.bt_picture_search);
        recyclerView=view.findViewById(R.id.rv_news);
        adapter=new NewsAdapter(dataList,getContext());
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
        viewPager2=view.findViewById(R.id.viewpager2);
        indicatorContainer=view.findViewById(R.id.container_indicator);
        colors.add(R.drawable.a);
        colors.add(R.drawable.b);
        colors.add(R.drawable.c);
        colors.add(R.drawable.d);
        initIndicatorDots();
        //添加适配器
        ViewPaperAdapter viewPagerAdapter = new ViewPaperAdapter(colors);
        viewPager2.setAdapter(viewPagerAdapter);
        viewPager2.setCurrentItem(500);
        lastPosition = 500;
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                int current = position % 4;
                int last = lastPosition % 4;
                indicatorContainer.getChildAt(current).setBackgroundResource(R.drawable.shape_dot_selected);
                indicatorContainer.getChildAt(last).setBackgroundResource(R.drawable.shape_dot);
                lastPosition = position;
            }
        });

        //滑动界面

        collapsingToolbarLayout = view.findViewById(R.id.toolbar_layout);
        appBarLayout = view.findViewById(R.id.appbar_layout);
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            boolean isShow = true;
            int scrollRange = -1;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (scrollRange == -1) {
                    scrollRange = appBarLayout.getTotalScrollRange();
                }
                if (scrollRange + verticalOffset == 0) {//收缩时
                    collapsingToolbarLayout.setTitle("垃圾分类");
                    isShow = true;
                } else if (isShow) {//展开时
                    collapsingToolbarLayout.setTitle("");
                    isShow = false;
                }
            }
        });


        TextSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent text=new Intent();
                text.setClass(getActivity(), textSearch.class);
                startActivity(text);

            }
        });

        VoiceSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               startActivity(new Intent(getActivity(), com.example.goodtrash.search.VoiceSearch.class));
            }
        });
        pictureSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), imageSearch.class));
            }
        });
       return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        showLoadingDialog();
        queryHotSearch();

    }

     final Runnable runnable=new Runnable() {
         @Override
         public void run() {
             int currentPosition = viewPager2.getCurrentItem();
             currentPosition++;
             viewPager2.setCurrentItem(currentPosition,true);
             mHandler.postDelayed(runnable,5000);
         }
     };

    @Override
    public void onResume() {
        super.onResume();
        mHandler.postDelayed(runnable,5000);
    }

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacks(runnable);
    }

    public void queryHotSearch(){
        HttpUtil.sendHotSearchRequest(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                closeProgressDialog();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getContext(),"获取失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseText=response.body().string();

               HotSearch hotSearch=Utility.handleNewsResponse(responseText);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (hotSearch!=null&&"success".equals(hotSearch.getMsg())){
                            closeProgressDialog();
                            dataList.clear();
                            List<News> newsList=hotSearch.getNewsList();
                            for (News news : newsList){
                                dataList.add(news);
                            }
                            adapter.notifyDataSetChanged();
                        }else {
                            closeProgressDialog();
                            Toast.makeText(getContext(),"解析失败",Toast.LENGTH_SHORT).show();
                        }

                    }
                });

            }
        });
    }
    private void showLoadingDialog(){
        if(progressDialog==null){
            progressDialog=new ProgressDialog(getContext());
            progressDialog.setMessage("正在加载.....");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    private void closeProgressDialog(){
        if(progressDialog!=null){
            progressDialog.dismiss();
        }
    }
    private void initIndicatorDots(){
        for(int i = 0; i < colors.size(); i++){
            ImageView imageView = new ImageView(getContext());
            if (i == 0) imageView.setBackgroundResource(R.drawable.shape_dot_selected);
            else imageView.setBackgroundResource(R.drawable.shape_dot);
            //为指示点添加间距
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.setMarginEnd(4);
            imageView.setLayoutParams(layoutParams);
            //将指示点添加进容器
            indicatorContainer.addView(imageView);
        }
    }


}

